package com.oazon.moco.playlist.db;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.oazon.common.TaskHelper;
import com.oazon.moco.bean.AuthType;
import com.oazon.moco.bean.DeviceLinkAuthParams;
import com.oazon.moco.bean.McServiceMsg;
import com.oazon.moco.bean.ProviderAdapt;
import com.oazon.moco.bean.SessionIdAuthParams;
import com.oazon.moco.playlist.PlayListManage;
import com.oazon.moco.playlist.bean.ResourceBean;
import com.oazon.sonos.core.SonosControler;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ServiceMsgDao {

	private SQLiteDatabase db;
	
	private static final String TABLE_NAME = "service_msg";
	private static final String C_CREAT_TIME = "creat_time";
	private static final String C_LIFE_TIME = "life_time";
	private static final String C_ID = "id";
	private static final String C_UUID = "uuid";
	private static final String C_PROVIDER_NAME = "provider_name";
	private static final String C_AUTH_TYPE = "auth_type";
	private static final String C_URI = "uri";
	private static final String C_SECURE_URI = "secure_uri";
	private static final String C_SESSION_ID = "session_id";
	private static final String C_TOKEN = "token";
	private static final String C_KEY = "key";
	private static final String C_DEVICE_PROVIDER = "device_provider";
	private static final String C_HOUSEHOLD_ID = "household_id";
	private static final String C_LINK_CODE = "link_code";
	private static final String C_LINK_DEVICE_ID = "link_device_id";
	
	List<McServiceMsg> serviceMsgs = null; 
	
	private static ServiceMsgDao object = null;
	
	public synchronized static ServiceMsgDao getInstance(Context context){
		if(object == null){
			object = new ServiceMsgDao(context);
		}
		return object;
	}

	private ServiceMsgDao(Context context) {
		MocoDB resourceDB = new MocoDB(context);
		db = resourceDB.getReadableDatabase();
		TaskHelper.exec(new Runnable() {
			
			@Override
			public void run() {
				serviceMsgs = queryAll();
			}
		});
	}

	public McServiceMsg getServiceMsgByID(int id){
		if(serviceMsgs == null){
			return null;
		}
		for (McServiceMsg mcServiceMsg : serviceMsgs) {
			if(mcServiceMsg.getId() == id){
				return mcServiceMsg;
			}
		}
		return null;
	}
	public McServiceMsg getServiceMsgByProvider(String provider){
		return getServiceMsgByID(ProviderAdapt.provider2id(provider));
	}
	
	public synchronized long insertIntoServiceMsg(McServiceMsg msg) {
		if(msg == null){
			return -1l;
		}
		deleteById(msg.getId());
		
		serviceMsgs.add(msg);
		
		ContentValues values = new ContentValues();
		String time = new Date().toString();

		values.put(C_CREAT_TIME, time);
		values.put(C_LIFE_TIME, "0");
		values.put(C_ID, msg.getId());
		values.put(C_UUID, msg.getUuid());
		values.put(C_PROVIDER_NAME, msg.getName());
		values.put(C_AUTH_TYPE, msg.getAuthType());
		values.put(C_URI, msg.getUri());
		values.put(C_SECURE_URI, msg.getSecureUri());

		if (msg.getAuthParams() != null) {
			if (msg.getAuthParams() instanceof SessionIdAuthParams) {
				values.put(C_SESSION_ID, ((SessionIdAuthParams) msg
						.getAuthParams()).getSessionId());

			} else if (msg.getAuthParams() instanceof DeviceLinkAuthParams) {

				DeviceLinkAuthParams param = (DeviceLinkAuthParams) msg
						.getAuthParams();
				values.put(C_TOKEN, param.getToken());
				values.put(C_KEY, param.getKey());
				values.put(C_DEVICE_PROVIDER, param.getDeviceProvider());
				values.put(C_HOUSEHOLD_ID, param.getHouseholdid());
				values.put(C_LINK_CODE, param.getLinkCode());
				values.put(C_LINK_DEVICE_ID, param.getLinkDeviceId());
			}
		}
		return db.insert(TABLE_NAME, "", values);
	}

	public synchronized int deleteById(int id) {
		int index =-1;
		if(serviceMsgs == null ||serviceMsgs.size()<=0){
			return -1;
		}
		for (int i = 0; i < serviceMsgs.size(); i++) {
			if(serviceMsgs.get(i).getId() == id){
				index = i;
				break;
			}
		}
		if(index > -1){
			serviceMsgs.remove(index);
//TODO Gavin	假如删除了音乐服务，而队列里又有这些服务的歌曲，只要不删除Soap就可以正常播放
//			SonosControler.deleteSoapById(id);
				
			return db.delete(TABLE_NAME, C_ID + "=?", new String[] { String.valueOf(id) });
		}
		return -1;

	}
	
	public List<McServiceMsg> getAll(){
		return serviceMsgs;
	}
	
	private List<McServiceMsg> queryAll(){
		List<McServiceMsg> msgs = new ArrayList<McServiceMsg>();
		Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
				null, C_CREAT_TIME, null);
		while (cursor.moveToNext()) {
			McServiceMsg msg = new McServiceMsg();
			msg.setId(cursor.getInt(cursor.getColumnIndex(C_ID)));
			msg.setName(cursor.getString(cursor.getColumnIndex(C_PROVIDER_NAME)));
			msg.setSecureUri(cursor.getString(cursor.getColumnIndex(C_SECURE_URI)));
			msg.setUri(cursor.getString(cursor.getColumnIndex(C_URI)));
			msg.setUuid(cursor.getString(cursor.getColumnIndex(C_UUID)));
			msg.setAuthType(cursor.getString(cursor.getColumnIndex(C_AUTH_TYPE)));
			
			String authType = msg.getAuthType();
			
			if(authType.equals(AuthType.SESSION_ID.value())){
				SessionIdAuthParams param = new SessionIdAuthParams();
				param.setSessionId(cursor.getString(cursor.getColumnIndex(C_SESSION_ID)));
				msg.setAuthParams(param);
				
			}else if(authType.equals(AuthType.DEVICE_LINK.value())){
				DeviceLinkAuthParams param = new DeviceLinkAuthParams();
				param.setToken(cursor.getString(cursor.getColumnIndex(C_TOKEN)));
				param.setKey(cursor.getString(cursor.getColumnIndex(C_KEY)));
				param.setHouseholdid(cursor.getString(cursor.getColumnIndex(C_HOUSEHOLD_ID)));
				param.setDeviceProvider(cursor.getString(cursor.getColumnIndex(C_DEVICE_PROVIDER)));
				param.setLinkCode(cursor.getString(cursor.getColumnIndex(C_LINK_CODE)));
				param.setLinkDeviceId(cursor.getString(cursor.getColumnIndex(C_LINK_DEVICE_ID)));
				msg.setAuthParams(param);
			}
			msgs.add(msg);
		}
		cursor.close();
		return msgs;
	}
}
